package com.i3q360.layui.core.shiro;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.i3q360.layui.common.util.SpringContextHolder;
import com.i3q360.layui.modular.system.entity.SysPermission;
import com.i3q360.layui.modular.system.entity.SysRole;
import com.i3q360.layui.modular.system.entity.UserInfo;
import com.i3q360.layui.modular.system.service.UserInfoService;


public class ShiroDbRealm extends AuthorizingRealm{

	private Logger log = LoggerFactory.getLogger(ShiroDbRealm.class);
	
	@Resource
    private UserInfoService userInfoService;
	@Resource
	RetryLimitMatcher matcher;
	
    /**
     * 登录认证
     */
    @Override
    protected AuthorizationInfo  doGetAuthorizationInfo(PrincipalCollection  principals)
            throws AuthenticationException {
    	System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
    	 SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
    	 UserInfo userInfo  = (UserInfo)principals.getPrimaryPrincipal();
    	 
    	 for(SysRole role:userInfo.getRoleList()){
             authorizationInfo.addRole(role.getRole());
             for(SysPermission p:role.getPermissions()){
                 authorizationInfo.addStringPermission(p.getPermission());
             }
         }
         return authorizationInfo;
    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        log.info("MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        UserInfo userInfo = userInfoService.findByUsername(username);
        if(userInfo == null){
            // 用户名不存在抛出异常
            throw new UnknownAccountException();
        }
        if(matcher.isLocked(username)){
        	throw new LockedAccountException();
        }
        
        userInfo.setRoleNames();
        log.info("----->>userInfo="+userInfo);
        log.info("roleNames is {}",userInfo.getRoleNames());
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo, //用户名
                userInfo.getPassword(), //密码
                ByteSource.Util.bytes(userInfo.getCredentialsSalt()),//salt=username+salt
                getName()  //realm name
        );
        return authenticationInfo;
    }
    
    @Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher){
    	   HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
           md5CredentialsMatcher.setHashAlgorithmName(ShiroKit.hashAlgorithmName);
           md5CredentialsMatcher.setHashIterations(ShiroKit.hashIterations);
           super.setCredentialsMatcher(md5CredentialsMatcher);
	}
	
    
}
	